<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="业务员" prop="staffId">
            <el-select
                v-model="queryConditions.staffId"
                style="width: 200px"
                size="large"
                placeholder="请选择"
                clearable
            >
                <el-option
                    v-for="staff in staffList"
                    :key="staff.id"
                    :label="staff.name"
                    :value="staff.id"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
            <el-select
                v-model="queryConditions.supplierId"
                style="width: 200px"
                size="large"
                placeholder="请选择"
                clearable
            >
                <el-option
                    v-for="supplier in supplierList"
                    :key="supplier.id"
                    :label="supplier.name"
                    :value="supplier.id"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
            <el-date-picker
                v-model="queryConditions.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="large"
            />
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>
    <SalesOrderSummaryLimitPage
        :table-data="formattedTableData"
        :columns="tableColumns"
        :current-page="pageNo"
        :total="allPage"
        :page-size="pageSize"
        @page-change="handlePageChange"
        @action="handleTableAction"
    />
</template>

<script setup lang="ts">
import {onMounted} from 'vue';
import {Search, RefreshRight} from '@element-plus/icons-vue';
import {ref, computed, reactive, nextTick} from 'vue';
import {ElMessage, type FormInstance, ElLoading} from 'element-plus';
import SalesOrderSummaryLimitPage from "@/salesOrderSummary/SalesOrderSummaryLimitPage.vue";
import request from "@/util/request.ts";

let pageNo = ref(1);
let pageSize = ref(10);
let allPage = ref(0);
const searchFormRef = ref<FormInstance>();

// 查询条件
const queryConditions = reactive({
    staffId: null,
    supplierId: null,
    dateRange: [],
    status: null
});

// 查询
const search = () => {
    pageNo.value = 1; // 重置到第一页
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        queryConditions.staffId = null;
        queryConditions.supplierId = null;
        queryConditions.dateRange = [];
        queryConditions.status = null;
        pageNo.value = 1;
        fetchData(1);
    });
};

let tableData = ref<any[]>([]);

// 格式化表格数据
const formattedTableData = computed(() => {
    return tableData.value.map((item, index) => ({
        ...item,
        index: (pageNo.value - 1) * pageSize.value + index + 1,
        year: item.year || '未知年份',
        month: item.month || '未知月份',
        totalAmount: Number(item.totalAmount).toFixed(2),
        totalAmountWithTax: Number(item.totalAmountWithTax).toFixed(2),
        getAmount: Number(item.getAmount).toFixed(2),
        waitAmount: Number(item.waitAmount || 0).toFixed(2),
        waitAmountWithTax: Number(item.waitAmountWithTax || 0).toFixed(2),
        finishAmount: Number(item.finishAmount).toFixed(2),
        finishAmountWithTax: Number(item.finishAmountWithTax).toFixed(2),
        staffName: item.staffName || '未知业务员',
        supplierName: item.supplierName || '未知供应商'
    }));
});

// 表格列配置
const tableColumns = ref([
    {prop: 'index', label: '序号', width: 80},
    {prop: 'year', label: '年', width: 80},
    {prop: 'month', label: '月', width: 80},
    {prop: 'staffId', label: '业务员ID', width: 120},
    {prop: 'staffName', label: '业务员', width: 150},
    {prop: 'supplierId', label: '供应商ID', width: 120},
    {prop: 'supplierName', label: '供应商', width: 150},
    {prop: 'orderCount', label: '订单笔数', width: 120},
    {prop: 'totalAmount', label: '采购金额', width: 150},
    {prop: 'totalAmountWithTax', label: '采购金额(税)', width: 150},
    {prop: 'getAmount', label: '入库金额', width: 150},
    {prop: 'waitAmount', label: '未结算金额', width: 150},
    {prop: 'waitAmountWithTax', label: '未结算金额(税)', width: 150},
    {prop: 'finishAmount', label: '结算金额', width: 150},
    {prop: 'finishAmountWithTax', label: '结算金额(税)', width: 150}
]);

// 分页处理
const handlePageChange = (newPage: number) => {
    pageNo.value = newPage;
    fetchData(newPage);
};

// 导出数据
const handleExport = async () => {
    const params = {
        pageNo: pageNo.value,
        pageSize: pageSize.value,
        staffId: queryConditions.staffId,
        supplierId: queryConditions.supplierId,
        startDate: queryConditions.dateRange[0] ? queryConditions.dateRange[0].toISOString().split('T')[0] : null,
        endDate: queryConditions.dateRange[1] ? queryConditions.dateRange[1].toISOString().split('T')[0] : null,
        status: queryConditions.status
    };
    const loading = ElLoading.service({text: "正在导出..."});
    try {
        const response = await request.post(
            "/cg/PurchaseOrderSummary/exportSummaryByStaff",
            params,
            {responseType: "blob"}
        );
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "业务员采购订单汇总.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success("导出成功");
    } catch (error) {
        console.error("导出失败:", error);
        ElMessage.error("导出失败，请稍后重试");
    } finally {
        loading.close();
    }
};

// 处理表格操作
const handleTableAction = (actionName: string) => {
    if (actionName === 'export') {
        handleExport();
    }
};

// 获取数据
async function fetchData(page: number) {
    try {
        const response = await request.post('/cg/PurchaseOrderSummary/selectSummaryByStaff', {
            pageNo: page,
            pageSize: pageSize.value,
            staffId: queryConditions.staffId,
            supplierId: queryConditions.supplierId,
            startDate: queryConditions.dateRange[0] ? queryConditions.dateRange[0].toISOString().split('T')[0] : null,
            endDate: queryConditions.dateRange[1] ? queryConditions.dateRange[1].toISOString().split('T')[0] : null,
            status: queryConditions.status
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
    } catch (error) {
        ElMessage.error('获取业务员汇总数据失败');
        tableData.value = [];
        allPage.value = 0;
    }
}

// 获取业务员列表
const staffList = ref<any[]>([]);
const fetchAllStaffs = async () => {
    try {
        const res = await request.post('/public/User/selectAllUser');
        staffList.value = res.data.data;
    } catch (e) {
        ElMessage.error('获取业务员数据失败');
        staffList.value = [];
    }
};

// 获取供应商列表
const supplierList = ref<any[]>([]);
const fetchAllSuppliers = async () => {
    try {
        const res = await request.post('/basic/Provider/selectAllSupplier');
        supplierList.value = res.data.data;
    } catch (e) {
        ElMessage.error('获取供应商数据失败');
        supplierList.value = [];
    }
};

onMounted(() => {
    fetchData(1);
    fetchAllStaffs();
    fetchAllSuppliers();
});
</script>

<style scoped>
</style>
